<?php
/**
 * Created by PhpStorm.
 * User: Lionel
 * Date: 2015/4/27
 * Time: 18:10
 */

namespace common\utils;

use Yii;

class DomainUtil
{
    public static function getDomainLink($server, $uri, $isSsl = true)
    {
        if ($uri != '') {
            if ($uri[0] != '/') $uri = '/' . $uri;
        }
        $domain = Yii::$app->params['domains'][$server];
        if ($domain == '') return $uri;

        $protocol = $isSsl ? "https" : "http";
        return "$protocol://$domain$uri";
    }

    public static function getOpenmsnDomainLink($uri, $isSsl = true)
    {
        if ($uri != '' && $uri[0] != '/') {
            $uri = '/' . $uri;
        }
        $domain = 'openmsn.' . Yii::$app->params['domains']['RootDomain'];
        $protocol = $isSsl ? "https" : "http";
        return "$protocol://$domain$uri";
    }

    /**
     * 根据不同微信站点来源返回站点路径
     *     保证同一站点只访问自己站点的资源，该功能实现通过nginx反向代理处理
     *     当代码被云采购公众号和采招公众号共用时，调用该方法；如果有未被涵盖的站点处理，此处可以增加相应处理     *
     * @param $server
     * @param $uri
     * @param bool $isSsl
     * @return string
     */
    public static function getDomainLinkByOrigin($server, $uri, $isSsl = true)
    {
        if(!empty($_SERVER["HTTP_WEIXINTYPE"])){
            $from=$_SERVER["HTTP_WEIXINTYPE"];
            if($from=="qy"){
                switch($server) {
                    case "WapStatic":
                        $server = "QyWapStatic";
                        break;
                    case "WapNet":
                        $server = "WapCzwxh";
                        break;
                    default:
                }
            }
        }

        return  self::getDomainLink($server, $uri, $isSsl);
    }

    public static function getImgDynamicDomainLink($server, $uri, $isSsl = true)
    {
        $url = self::getDomainLink($server, $uri, $isSsl);
        if (empty($url)) {
            return $url;
        }
        $dotIndex = strpos($url, '.');
        if ($dotIndex === false) {
            return $url;
        }

        $num = abs(self::hashCode($url)) % 5 + 1;
        $url = substr($url, 0, $dotIndex) . $num . substr($url, $dotIndex);

        return $url;
    }

    private static function hashCode($s)
    {
        $len = strlen($s);
        $hash = 0;
        for ($i = 0; $i < $len; $i++) {
            //一定要转成整型
            $hash = (int)($hash * 31 + ord($s[$i]));
            //64bit下判断符号位
            if (($hash & 0x80000000) == 0) {
                //正数取前31位即可
                $hash &= 0x7fffffff;
            } else {
                //负数取前31位后要根据最小负数值转换下
                $hash = ($hash & 0x7fffffff) - 2147483648;
            }
        }
        return $hash;
    }


    /*
     *  获取根域名 如：mycaigou.com
     * */
    public static function  getRootDomain()
    {
        $domain = Yii::$app->params['domains']["RootDomain"];
        return $domain;

    }

}
